package org.inasnet.user;

import java.io.File;

import org.inasnet.Config;
import org.inasnet.Root;
import org.inasnet.user.Session.SessionCancelled;
/**
 * Client user overlaps custom User. 
 */
public class ClientUser extends User 
{
	public ClientUser( String accountId )
	{
		mContactList.restoreFromConfig( accountId );
		
		mConfig = new UserConfig( accountId );
		
		String dbgAuthIp = null;
		
		String [] strs = accountId.split( "_" );
		
		mId = Integer.parseInt( strs[ 0 ] );
		
		try 
		{
			// from Base
			
			mHashPassword = getConfigValue( "password" );
			
			Root.loadLangPack( getConfigValue( "lang" ) );
			
			mAuthServer = new AuthServer( mConfig.get( "auth_server" ), ConnectionSettings.mAuthAppServerPort );
			
			/*
			 * DEBUG TODO:DELETE
			 */
			
			try 
			{
				dbgAuthIp = getConfigValue( "_auth_ip" );
			} 
			catch( Exception e ) 
			{
				dbgAuthIp = null;
			}
		} 
		catch( Exception e ) 
		{
			e.printStackTrace();
		}
		
		mConnector = new UserConnector();
		
		if( dbgAuthIp != null )
		{
			mConnector._DBGAuthIp( dbgAuthIp );
		}
		
		setStatus( Status.ONLINE );
	}

	public ContactList getContactList()
	{
		return mContactList;
	}
	
	public void doSession() 
	{
		mConnector.doSession();
	}
	
	class UserConfig extends Config
	{
		UserConfig( String accountId )
		{
			super( "config/users/" + accountId + "/config.txt" );
		}
	}
	
	String getConfigValue( String key ) throws Exception
	{
		return mConfig.get( key );
	}
	
	public String getHashPassword() 
	{
		return mHashPassword;
	}
	
	public void startUp() 
	{
		mConnector.authorize();
	}
	
	public static String detectUser() throws Exception
	{
		//return null;
		
		File file = new File( "config/users" );
		
		String[] user = file.list();
		
		String userFound = null;
		
		for( int i = 0; i < user.length; i++ )
		{
			if( user[ i ].matches( "[0-9]" ) )
			{
				if( userFound == null )
					userFound = user[ i ];
				else
				{
					userFound = null;
					throw new Exception( "More than two users detected!" );
				}
			}			
		}
		
		return userFound;
	}
	
	public void contactUser( User user )
	{
		try
		{
			mConnector.addSession( new Session( user ) );
		}
		catch( SessionCancelled e )
		{
			e.printStackTrace();
		}
	}
	
	ContactList mContactList = new ContactList();
	
	UserConnector mConnector;
	
	UserConfig mConfig;

	String mHashPassword;
	
	AuthServer mAuthServer;

	
}
